// 封装api返回格式扩展
module.exports = {
  // 成功提示
  apiSuccess(data = '', msg = 'ok', code = 200) {
    this.body = { msg, data, code };
    this.status = code;
  },
  // 失败提示
  apiFail(data = '', msg = 'fail', code = 201) {
    this.body = { msg, data, code };
    this.status = code;
  },

  // 生成token
  getToken(value) {
    return this.app.jwt.sign(value, this.app.config.jwt.secret);
  },

  // 验证token
  checkToken(token) {
    return this.app.jwt.verify(token, this.app.config.jwt.secret);
  },

  // 生成唯一id
  genID(length) {
    return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36);
  },

  // 参数验证
  parameter(obj) {
    let str = '';
    for (let item in obj) {
      if (obj[item] === undefined) {
        str = `参数值错误：${item} 为undefined`
        break
      }
      if (obj[item] === '') {
        str = `参数值验证：${item} 为必填项`
        break
      }
    }
    return str;
  },
  // 时间戳转换成字符串 如：2023-01-01 12:30:00
  formatTimestamp(timestamp) {
    const currentDate = new Date(timestamp);

    const year = currentDate.getFullYear();
    const month = ('0' + (currentDate.getMonth() + 1)).slice(-2);
    const day = ('0' + currentDate.getDate()).slice(-2);
    const hours = ('0' + currentDate.getHours()).slice(-2);
    const minutes = ('0' + currentDate.getMinutes()).slice(-2);
    const seconds = ('0' + currentDate.getSeconds()).slice(-2);

    const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    return formattedDateTime;
  }
};